package com.southminority.ethnic.service.contact.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.southminority.ethnic.mapper.contact.CooperationFileMapper;
import com.southminority.ethnic.pojo.CooperationFile;
import com.southminority.ethnic.service.contact.CooperationFileService;
import com.southminority.ethnic.service.alioss.OssService;
import com.southminority.ethnic.controller.contact.vo.CooperationFileVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合作申请文件服务实现类
 * 
 * @author SouthMinority
 */
@Slf4j
@Service
public class CooperationFileServiceImpl implements CooperationFileService {

    private final CooperationFileMapper cooperationFileMapper;
    private final OssService ossService;

    public CooperationFileServiceImpl(CooperationFileMapper cooperationFileMapper, OssService ossService) {
        this.cooperationFileMapper = cooperationFileMapper;
        this.ossService = ossService;
    }

    @Override
    public List<CooperationFileVO> getActiveFiles() {
        List<CooperationFile> files = cooperationFileMapper.selectByStatus(1);
        return files.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public CooperationFileVO getDefaultFile() {
        CooperationFile file = cooperationFileMapper.selectDefaultFile();
        if (file == null) {
            // 如果没有默认文件，返回第一个启用的文件
            List<CooperationFile> files = cooperationFileMapper.selectByStatus(1);
            if (!files.isEmpty()) {
                file = files.get(0);
            }
        }
        return file != null ? convertToVO(file) : null;
    }

    @Override
    public List<CooperationFileVO> getFilesByType(String fileType) {
        List<CooperationFile> files = cooperationFileMapper.selectByFileTypeAndStatus(fileType, 1);
        return files.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public CooperationFileVO getFileDetail(Long id) {
        CooperationFile file = cooperationFileMapper.selectByIdAndStatus(id, 1);
        return file != null ? convertToVO(file) : null;
    }

    @Override
    public void downloadFile(Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            CooperationFile file = cooperationFileMapper.selectByIdAndStatus(id, 1);
            if (file == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 增加下载次数
            incrementDownloadCount(id);

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", 
                "attachment; filename=\"" + file.getFileName() + "\"");

            // 重定向到文件URL（如果是OSS链接）
            if (file.getFileUrl().startsWith("http")) {
                response.sendRedirect(file.getFileUrl());
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (IOException e) {
            log.error("下载文件失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public void incrementDownloadCount(Long id) {
        cooperationFileMapper.incrementDownloadCount(id);
    }

    // ==================== 管理端方法实现 ====================

    @Override
    public List<CooperationFileVO> getAllFiles() {
        LambdaQueryWrapper<CooperationFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(CooperationFile::getStatus, -1) // 不包括已删除的
                .orderByAsc(CooperationFile::getSortOrder)
                .orderByDesc(CooperationFile::getCreateTime);
        
        List<CooperationFile> files = cooperationFileMapper.selectList(queryWrapper);
        return files.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public CooperationFileVO getFileDetailAdmin(Long id) {
        LambdaQueryWrapper<CooperationFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CooperationFile::getId, id)
                .ne(CooperationFile::getStatus, -1);
        
        CooperationFile file = cooperationFileMapper.selectOne(queryWrapper);
        return file != null ? convertToVO(file) : null;
    }

    @Override
    @Transactional
    public CooperationFileVO uploadFile(MultipartFile file, String title, String description, String version, Boolean isDefault) {
        try {
            // 上传文件到OSS
            String fileUrl = ossService.upload(file, "cooperation");
            
            // 创建文件记录
            CooperationFile cooperationFile = new CooperationFile();
            cooperationFile.setTitle(title);
            cooperationFile.setDescription(description);
            cooperationFile.setFileType("cooperation_form");
            cooperationFile.setFileUrl(fileUrl);
            cooperationFile.setFileName(file.getOriginalFilename());
            cooperationFile.setFileSize(file.getSize());
            cooperationFile.setFileFormat(getFileExtension(file.getOriginalFilename()));
            cooperationFile.setVersion(version);
            cooperationFile.setDownloadCount(0);
            cooperationFile.setSortOrder(0);
            cooperationFile.setIsDefault(isDefault ? 1 : 0);
            cooperationFile.setStatus(1);

            if (isDefault) {
                clearOtherDefaultFiles();
            }

            cooperationFileMapper.insert(cooperationFile);
            log.info("cooperation file saved: id={}", cooperationFile.getId());
            return convertToVO(cooperationFile);
            
        } catch (Exception e) {
            log.error("upload error", e);
            throw new RuntimeException("上传文件失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public CooperationFileVO updateFile(Long id, CooperationFileVO fileVO) {
        CooperationFile existingFile = cooperationFileMapper.selectById(id);
        if (existingFile == null || existingFile.getStatus() == -1) {
            return null;
        }

        // 更新文件信息
        existingFile.setTitle(fileVO.getTitle());
        existingFile.setDescription(fileVO.getDescription());
        existingFile.setVersion(fileVO.getVersion());
        existingFile.setSortOrder(fileVO.getSortOrder());
        existingFile.setUpdateTime(new Date());

        // 处理默认文件设置
        if (fileVO.getDefaultFile() != null && fileVO.getDefaultFile()) {
            if (existingFile.getIsDefault() != 1) {
                clearOtherDefaultFiles();
                existingFile.setIsDefault(1);
            }
        } else {
            existingFile.setIsDefault(0);
        }

        cooperationFileMapper.updateById(existingFile);
        return convertToVO(existingFile);
    }

    @Override
    @Transactional
    public boolean deleteFile(Long id) {
        CooperationFile file = cooperationFileMapper.selectById(id);
        if (file == null) {
            return false;
        }

        // 逻辑删除
        file.setStatus(-1);
        file.setUpdateTime(new Date());
        
        return cooperationFileMapper.updateById(file) > 0;
    }

    @Override
    @Transactional
    public int batchDeleteFiles(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }

        LambdaUpdateWrapper<CooperationFile> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(CooperationFile::getId, ids)
                .set(CooperationFile::getStatus, -1)
                .set(CooperationFile::getUpdateTime, new Date());

        return cooperationFileMapper.update(null, updateWrapper);
    }

    @Override
    @Transactional
    public boolean setDefaultFile(Long id, boolean isDefault) {
        CooperationFile file = cooperationFileMapper.selectById(id);
        if (file == null || file.getStatus() != 1) {
            return false;
        }

        if (isDefault) {
            // 设置为默认：先取消其他文件的默认状态
            clearOtherDefaultFiles();
            file.setIsDefault(1);
        } else {
            // 取消默认：直接设置为非默认
            file.setIsDefault(0);
        }
        
        file.setUpdateTime(new Date());
        return cooperationFileMapper.updateById(file) > 0;
    }

    @Override
    public boolean updateFileStatus(Long id, Integer status) {
        CooperationFile file = cooperationFileMapper.selectById(id);
        if (file == null) {
            return false;
        }

        file.setStatus(status);
        file.setUpdateTime(new Date());
        
        return cooperationFileMapper.updateById(file) > 0;
    }
    

    /**
     * 清除其他文件的默认状态
     */
    private void clearOtherDefaultFiles() {
        LambdaUpdateWrapper<CooperationFile> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CooperationFile::getIsDefault, 1)
                .set(CooperationFile::getIsDefault, 0)
                .set(CooperationFile::getUpdateTime, new Date());
        
        cooperationFileMapper.update(null, updateWrapper);
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || !filename.contains(".")) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
    }

    /**
     * 将实体转换为VO
     */
    private CooperationFileVO convertToVO(CooperationFile file) {
        CooperationFileVO vo = new CooperationFileVO();
        BeanUtils.copyProperties(file, vo);
        
        // 设置显示字段
        vo.setFileTypeDisplay(getFileTypeDisplay(file.getFileType()));
        vo.setFileSizeDisplay(getFileSizeDisplay(file.getFileSize()));
        vo.setDefaultFile(file.getIsDefault() != null && file.getIsDefault() == 1);
        vo.setStatusDisplay(getStatusDisplay(file.getStatus()));
        vo.setDownloadUrl("/api/contact/cooperation-files/download/" + file.getId());
        
        return vo;
    }

    /**
     * 获取文件类型显示名称
     */
    private String getFileTypeDisplay(String fileType) {
        if ("cooperation_form".equals(fileType)) {
            return "合作申请表";
        }
        return fileType;
    }

    /**
     * 获取文件大小显示
     */
    private String getFileSizeDisplay(Long fileSize) {
        if (fileSize == null || fileSize == 0) {
            return "未知";
        }
        
        if (fileSize < 1024) {
            return fileSize + " B";
        } else if (fileSize < 1024 * 1024) {
            return String.format("%.1f KB", fileSize / 1024.0);
        } else {
            return String.format("%.1f MB", fileSize / (1024.0 * 1024.0));
        }
    }

    /**
     * 获取状态显示名称
     */
    private String getStatusDisplay(Integer status) {
        switch (status) {
            case 1:
                return "启用";
            case 0:
                return "禁用";
            case -1:
                return "已删除";
            default:
                return "未知";
        }
    }
} 